//
//  VRGCalendarView.m
//  Vurig
//
//  Created by in 't Veen Tjeerd on 5/8/12.
//  Copyright (c) 2012 Vurig Media. All rights reserved.
//

#import "VRGCalendarView.h"
#import <QuartzCore/QuartzCore.h>
#import "NSDate+convenience.h"
#import "NSMutableArray+convenience.h"
#import "UIView+convenience.h"
#import "LunarCalendar.h"
#import "CYDatetime.h"

@interface VRGCalendarView ()
@property (nonatomic, strong) NSDateFormatter *formatter;
@end

@implementation VRGCalendarView

#pragma mark - Select Date
#pragma mark 获取日期的相关信息

-(void)selectDate:(NSInteger)date {

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit fromDate:self.currentMonth];
    [comps setDay:date];
    self.selectedDate = [gregorian dateFromComponents:comps];
    
    NSInteger selectedDateYear = [self.selectedDate year];
    NSInteger selectedDateMonth = [self.selectedDate month];
    NSInteger currentMonthYear = [self.currentMonth year];
    NSInteger currentMonthMonth = [self.currentMonth month];
    
    if (selectedDateYear < currentMonthYear) {
        if (self.qiehuanBtn.selected) {
            [self showPreviousWeek];
        } else {
            [self showPreviousMonth];
        }
        
    } else if (selectedDateYear > currentMonthYear) {
        if (self.qiehuanBtn.selected) {
            [self showNextWeek];
            
        } else {
            [self showNextMonth];
        }
    } else if (selectedDateMonth < currentMonthMonth) {
        if (self.qiehuanBtn.selected) {
            [self showPreviousWeek];
        } else {
            [self showPreviousMonth];
        }
    } else if (selectedDateMonth > currentMonthMonth) {
        if (self.qiehuanBtn.selected) {
            [self showNextWeek];
            
        } else {
            [self showNextMonth];
        }

    } else {
        [self setNeedsDisplay];
    }
    if ([self.delegate respondsToSelector:@selector(calendarView:dateSelected:)])
    {
        [self.delegate calendarView:self dateSelected:self.selectedDate];
    }

}

#pragma mark - Mark Dates
//NSArray can either contain NSDate objects or NSNumber objects with an int of the day.
-(void)markDates:(NSArray *)dates {
    self.markedDates = dates;
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    
    for (int i = 0; i<[dates count]; i++) {
        [colors addObject:[UIColor redColor]];
    }
    
    self.markedColors = [NSArray arrayWithArray:colors];
   
    
    [self setNeedsDisplay];
}

//NSArray can either contain NSDate objects or NSNumber objects with an int of the day.
-(void)markDates:(NSArray *)dates withColors:(NSArray *)colors {
    self.markedDates = dates;
    self.markedColors = colors;
    
    [self setNeedsDisplay];
}

#pragma mark - Set date to now
-(void)reset {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components =
    [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |
                           NSDayCalendarUnit) fromDate: [NSDate date]];
    self.currentMonth = [gregorian dateFromComponents:components]; //clean month
    
    [self updateSize];
    [self setNeedsDisplay];
    
    
    [self selectDate:[NSDate date].day];
}

#pragma mark - Next & Previous
-(void)showNextMonth {
    if (isAnimating) return;
    self.markedDates=nil;
    isAnimating=YES;
    prepAnimationNextMonth=YES;
    
    [self setNeedsDisplay];
    
    
    //Old month
    float oldSize = self.calendarHeight;
    UIImage *imageCurrentMonth = [self drawCurrentState];
    
    //New month
    self.currentMonth = [self.currentMonth offsetMonth:1];
    prepAnimationNextMonth=NO;
    
    
    [self setNeedsDisplay];
    
    UIImage *imageNextMonth = [self drawCurrentState];
    float targetSize = fmaxf(oldSize, self.calendarHeight);
    
    
    
    UIView *animationHolder = [[UIView alloc] initWithFrame:CGRectMake(0, kVRGCalendarViewTopBarHeight, kVRGCalendarViewWidth, targetSize-kVRGCalendarViewTopBarHeight)];
    [animationHolder setClipsToBounds:YES];
    [self addSubview:animationHolder];
    
    //Animate
    self.animationView_A = [[UIImageView alloc] initWithImage:imageCurrentMonth];
    self.animationView_B = [[UIImageView alloc] initWithImage:imageNextMonth];
    [animationHolder addSubview:self.animationView_A];
    [animationHolder addSubview:self.animationView_B];
    
   self.animationView_B.frameX = HARDWARE_SCREEN_WIDTH;
    
    //Animation
    __block VRGCalendarView *blockSafeSelf = self;
    [UIView animateWithDuration:0.35f
                     animations:^{
                      [self updateSize];
                    blockSafeSelf.animationView_A.frameX = - HARDWARE_SCREEN_WIDTH;
                    blockSafeSelf.animationView_B.frameX = 0;
                     }
                     completion:^(BOOL finished) {
                         [blockSafeSelf.animationView_A removeFromSuperview];
                         [blockSafeSelf.animationView_B removeFromSuperview];
                         blockSafeSelf.animationView_A=nil;
                         blockSafeSelf.animationView_B=nil;
                         isAnimating=NO;
                         [animationHolder removeFromSuperview];
                     }
     ];
}

-(void)showPreviousMonth {
    if (isAnimating) return;
    isAnimating=YES;
    self.markedDates=nil;
    //Prepare current screen
    prepAnimationPreviousMonth = YES;
    [self setNeedsDisplay];
    float oldSize = self.calendarHeight;
    UIImage *imageCurrentMonth = [self drawCurrentState];
    
    //Prepare next screen
    self.currentMonth = [self.currentMonth offsetMonth:-1];
    
    prepAnimationPreviousMonth=NO;
    
    [self setNeedsDisplay];
    UIImage *imagePreviousMonth = [self drawCurrentState];
    
    float targetSize = fmaxf(oldSize, self.calendarHeight);
    
    UIView *animationHolder = [[UIView alloc] initWithFrame:CGRectMake(0, kVRGCalendarViewTopBarHeight, kVRGCalendarViewWidth, targetSize-kVRGCalendarViewTopBarHeight)];
    
    [animationHolder setClipsToBounds:YES];
    [self addSubview:animationHolder];
    
    self.animationView_A = [[UIImageView alloc] initWithImage:imageCurrentMonth];
    self.animationView_B = [[UIImageView alloc] initWithImage:imagePreviousMonth];
    [animationHolder addSubview:self.animationView_A];
    [animationHolder addSubview:self.animationView_B];
    
    
    self.animationView_B.frameX = - HARDWARE_SCREEN_WIDTH;
    self.animationView_A.frameX = 0;
    __block VRGCalendarView *blockSafeSelf = self;
    [UIView animateWithDuration:0.35f
                     animations:^{
                         [self updateSize];
                    blockSafeSelf.animationView_B.frameX = 0;
                    blockSafeSelf.animationView_A.frameX = HARDWARE_SCREEN_WIDTH;
                     }
                     completion:^(BOOL finished) {
                         [blockSafeSelf.animationView_A removeFromSuperview];
                         [blockSafeSelf.animationView_B removeFromSuperview];
                         blockSafeSelf.animationView_A=nil;
                         blockSafeSelf.animationView_B=nil;
                         isAnimating=NO;
                         [animationHolder removeFromSuperview];
                     }
     ];
}


#pragma mark - update size & row count
-(void)updateSize {
    self.frameHeight = self.calendarHeight;
    self.qiehuanBtn.y = self.calendarHeight - self.qiehuanBtn.frameHeight;
    if ([self.delegate respondsToSelector:@selector(calendarView:switchedToMonthWithTargetHeight:animated:)]) {
        [self.delegate calendarView:self switchedToMonthWithTargetHeight:self.calendarHeight animated:YES];
    }
    [self setNeedsDisplay];
}

-(float)calendarHeight {
    return kVRGCalendarViewTopBarHeight + [self numRows] * kVRGCalendarViewDayHeight + 1 + self.qiehuanBtn.frameHeight;
}

-(NSInteger)numRows {
    
    NSInteger lastBlock = [self.currentMonth numDaysInMonth]+([self.currentMonth firstWeekDayInMonth] % 7);
    return (NSInteger)ceilf(lastBlock / 7.0f);
}

#pragma mark - Touches

- (void)selectedDateWithGesture:(UITapGestureRecognizer *)tap
{
    CGPoint touchPoint = [tap locationInView:self];
    self.selectedDate = nil;
    
    //Touch a specific day
    if (touchPoint.y > kVRGCalendarViewTopBarHeight) {
        float xLocation = touchPoint.x;
        float yLocation = touchPoint.y-kVRGCalendarViewTopBarHeight;
        
        int column = floorf(xLocation/(kVRGCalendarViewDayWidth));
        int row = floorf(yLocation/(kVRGCalendarViewDayHeight));
        
        int blockNr = (column + 1) + row * 7;
        NSInteger firstWeekDay = [self.currentMonth firstWeekDayInMonth]; //-1 because weekdays begin at 1, not 0
        NSInteger date = blockNr-firstWeekDay % 7;
        
        [self selectDate:date];
        return;
    }
    
    
    if (CGRectContainsPoint(self.labelCurrentMonth.frame, touchPoint)) {
        //Detect touch in current month
        [self reset];
    }

}

#pragma mark - Drawing 绘制日历
- (void)drawRect:(CGRect)rect
{
    CGContextClearRect(UIGraphicsGetCurrentContext(),rect);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetAllowsAntialiasing(context, NO);
    
    
    NSInteger firstWeekDay = [self.currentMonth firstWeekDayInMonth]; //-1 because weekdays begin at 1, not 0
    /**绘制日历的标题*/
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月"];
    self.labelCurrentMonth.text = [formatter stringFromDate:self.currentMonth];
    [self.labelCurrentMonth sizeToFit];
    
    /**计算日历标题文字的位置*/
    self.labelCurrentMonth.frameX = roundf(self.frame.size.width/2 - self.labelCurrentMonth.frameWidth/2);
    self.labelCurrentMonth.frameY = roundf((kVRGCalendarViewTopBarHeight - kVRGCalendarViewWeekDayHeight) / 2);
    [self.currentMonth firstWeekDayInMonth];
    
//  绘制日历格子背景
    CGRect rectangleGrid = CGRectMake(0,0,kVRGCalendarViewWidth,self.calendarHeight);
    CGContextAddRect(context, rectangleGrid);
    CGContextSetFillColorWithColor(context, WhiteColor.CGColor);
    CGContextFillPath(context);
    
    // 绘制周背景颜色
    CGRect background = CGRectMake(0, 55, kVRGCalendarViewWidth, kVRGCalendarViewWeekDayHeight - 10);
    CGContextAddRect(context, background);
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:252 / 255.0 green:246 / 255.0 blue:244 / 255.0 alpha:1.0].CGColor);
    CGContextFillPath(context);
    
    /**绘制标题的线条*/
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextBeginPath(context);
    CGContextSetLineWidth(context, .5);
    CGContextMoveToPoint(context, 0, kVRGCalendarViewTopBarHeight - kVRGCalendarViewWeekDayHeight + 11);
    CGContextAddLineToPoint(context, kVRGCalendarViewWidth, kVRGCalendarViewTopBarHeight - kVRGCalendarViewWeekDayHeight + 11);
    CGContextStrokePath(context);
    
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 10, kVRGCalendarViewTopBarHeight + 1);
    CGContextAddLineToPoint(context, kVRGCalendarViewWidth - 10, kVRGCalendarViewTopBarHeight + 1);
    CGContextStrokePath(context);
    
    // 绘制周内容
    NSArray *chineseWeekdays= [NSArray arrayWithObjects:@"一",@"二",@"三",@"四",@"五",@"六",@"日", nil];
    for (int i =0; i<[chineseWeekdays count]; i++) {
        
        if (i==5||i==6)
        {
            // 设置周六日 的颜色
            CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0xff3333" alpha:1.0].CGColor);
            
        } else {
            
            // set context fill color
            CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0xb5b5b5" alpha:1.0f].CGColor);
            
        }
       
        // add calendar weekday
        NSString *weekdayValue = (NSString *)[chineseWeekdays objectAtIndex:i];
        UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:14];

        // 绘制周字符串
        [weekdayValue drawInRect:CGRectMake(i*(kVRGCalendarViewDayWidth), 63, kVRGCalendarViewDayWidth, kVRGCalendarViewWeekDayHeight) withFont:font lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentCenter];
    }
    
    //Draw days
    CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0x383838" alpha:1.0f].CGColor);
    
    if (self.qiehuanBtn.selected) {
        
        
//            NSInteger todayBlock = -1;
//        
//            if ([todayDate month] == [self.currentMonth month] && [todayDate year] == [self.currentMonth year]) {
//                todayBlock = [todayDate day] + firstWeekDay - 1;
//            }
        
        for (int i=0; i < 7; i++) {
            
            CGFloat targetX = i * kVRGCalendarViewDayWidth;
            CGFloat targetY = kVRGCalendarViewTopBarHeight;
            
            CYDatetime *CYDate = [[CYDatetime alloc] init];
            CYDate.year=[self.currentMonth year];
            CYDate.month =[self.currentMonth month];
            if (self.selectedDate.year == self.currentMonth.year && self.selectedDate.month == self.currentMonth.month && self.selectedDate.day == self.currentMonth.day) {
                
            }
            CYDate.day = self.selectedDate.day + i - (self.selectedDate.week - 1) % 7;
            
            NSDate *grifDate = [CYDate convertDate];
            LunarCalendar *lunarCalendar = [grifDate chineseCalendarDate];
            
            NSString * lunarDate = lunarCalendar.DayLunar;
            
            
            NSString *date = [NSString stringWithFormat:@"%zd",grifDate.day];
            
            
            [self drawDaysWithgrifDate:grifDate targetX:targetX targetY:targetY targetColumn:i context:context date:date lunarDate:lunarDate];
        }
    } else {
        
#pragma mark -- 修改了日历标题
//        NSInteger firstWeekDay = [self.currentMonth firstWeekDayInMonth]; //-1 because weekdays begin at 1, not 0
        
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"yyyy年MM月"];
//        self.labelCurrentMonth.text = [formatter stringFromDate:self.currentMonth];
//        self.formatter = formatter;
//        [self.currentMonth firstWeekDayInMonth];
        
        NSInteger numRows = [self numRows];
        NSInteger numBlocks = numRows * 7;
        
        //Grid dark lines
//        CGContextSetStrokeColorWithColor(context, [UIColor colorWithHexString:@"0xcfd4d8" alpha:1.0f].CGColor);
        //  set grid color
//        CGContextSetStrokeColorWithColor(context, WhiteColor.CGColor);
//        
//        CGContextBeginPath(context);
//        for (int i = 0; i <= numRows; i++) {
//            CGContextMoveToPoint(context, 0, kVRGCalendarViewTopBarHeight + i * kVRGCalendarViewDayHeight);
//            CGContextAddLineToPoint(context, kVRGCalendarViewWidth, kVRGCalendarViewTopBarHeight + i * kVRGCalendarViewDayHeight);
//        }
//        CGContextStrokePath(context);
//        
//        CGContextSetAllowsAntialiasing(context, YES);

        
        for (int i=0; i<numBlocks; i++) {
            int targetColumn = i%7;
            int targetRow = i/7;
            
            CGFloat targetX = targetColumn * kVRGCalendarViewDayWidth;
            CGFloat targetY = kVRGCalendarViewTopBarHeight + targetRow * kVRGCalendarViewDayHeight;
            
            CYDatetime *CYDate = [[CYDatetime alloc]init];
            
            // BOOL isCurrentMonth = NO;
            
            //        CYDate.day = targetDate;
            
            CYDate.year=[self.currentMonth year];
            CYDate.month =[self.currentMonth month];
            CYDate.day = targetColumn + 1 + targetRow * 7 - firstWeekDay % 7;
            NSDate *grifDate = [CYDate convertDate];
            LunarCalendar *lunarCalendar = [grifDate chineseCalendarDate];
            
            NSString * lunarDate = lunarCalendar.DayLunar;
            
            
            NSString *date = [NSString stringWithFormat:@"%zd",grifDate.day];
            
            [self drawDaysWithgrifDate:grifDate targetX:targetX targetY:targetY targetColumn:targetColumn context:context date:date lunarDate:lunarDate];
        }
    }
    
    /**关闭上下文*/
    CGContextClosePath(context);
}


- (void)drawDaysWithgrifDate:(NSDate *)grifDate targetX:(CGFloat)targetX targetY:(CGFloat)targetY targetColumn:(NSInteger)targetColumn context:(CGContextRef)context date:(NSString *)date lunarDate:(NSString *)lunarDate
{
    BOOL isSelectedDatePreviousMonth = NO;
    BOOL isSelectedDateNextMonth = NO;
    
    if (self.currentMonth.year > grifDate.year) {
        isSelectedDatePreviousMonth = YES;
        isSelectedDateNextMonth = NO;
    } else if (self.currentMonth.year < grifDate.year) {
        isSelectedDateNextMonth = YES;
        isSelectedDatePreviousMonth = NO;
    } else {
        if (self.currentMonth.month < grifDate.month) {
            isSelectedDatePreviousMonth = NO;
            isSelectedDateNextMonth = YES;
            
        } else if(self.currentMonth.month == grifDate.month) {
            isSelectedDatePreviousMonth = NO;
            isSelectedDateNextMonth = NO;
            
        } else {
            isSelectedDatePreviousMonth = YES;
            isSelectedDateNextMonth = NO;
            
        }
    }
    
    
    
    NSString *hex1 = (isSelectedDatePreviousMonth || isSelectedDateNextMonth) ? @"0xaaaaaa" : @"0x383838";
    
    
    if(targetColumn==5||targetColumn==6)
    {
        if (isSelectedDatePreviousMonth || isSelectedDateNextMonth) {
            CGContextSetFillColorWithColor(context,[UIColor colorWithHexString:@"0xff3333" alpha:0.5f].CGColor);
        } else {
            
            CGContextSetFillColorWithColor(context,[UIColor colorWithHexString:@"0xff3333" alpha:1.0f].CGColor);
        }
    }
    else
    {
        CGContextSetFillColorWithColor(context,
                                       [UIColor colorWithHexString:hex1 alpha:1.0f].CGColor);
    }
    
    //画今天
    NSDate *todayDate = [NSDate date];
    if (todayDate.month == grifDate.month && todayDate.day == grifDate.day) {
        CGRect rectangleGrid = CGRectMake(targetX,targetY,kVRGCalendarViewDayWidth - 1,kVRGCalendarViewDayHeight - 1);
        CGContextAddRect(context, rectangleGrid);
        // 设置当天选中的颜色
        CGContextSetFillColorWithColor(context, WZRGBColor(84, 185, 254).CGColor);
//        CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0x383838" alpha:1.0f].CGColor);
//        CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
        
        CGContextFillPath(context);
        
        //画小图标
        CGRect alermRect = CGRectMake(targetX + kVRGCalendarViewDayWidth - 2.0f - 15.0f, targetY + 2.0f, 15.0f, 15.0f);
        /**设置提醒标注为*/
        CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0xffa500" alpha:1.0f].CGColor);
        CGContextFillEllipseInRect(context, alermRect);
        
        
        // 设置文字的颜色
        CGContextSetFillColorWithColor(context,
                                       [UIColor whiteColor].CGColor);
    }
    
#pragma mark -- 绘制选中的item
    //draw selected date
    if (self.selectedDate && grifDate.day == self.selectedDate.day && grifDate.month == self.selectedDate.month) {
        CGRect rectangleGrid = CGRectMake(targetX,targetY,kVRGCalendarViewDayWidth - 1,kVRGCalendarViewDayHeight - 1);
        CGContextAddRect(context, rectangleGrid);
        
        // 选中时的颜色
//                CGContextSetFillColorWithColor(context, WZRGBColor(233, 246, 255).CGColor);
        CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0x006dbc" alpha:1.0f].CGColor);
//        CGContextFillPath(context);
        
        CGContextFillPath(context);
        
        CGContextSetFillColorWithColor(context,
                                       [UIColor whiteColor].CGColor);
    }
    
    
    UIFont *dateFont = [UIFont fontWithName:@"HelveticaNeue-Bold" size:17.0f];
    UIFont *lunarDateFont = [UIFont fontWithName:@"HelveticaNeue" size:8.0f];
    
    
    CGFloat targetGap = (kVRGCalendarViewDayHeight - dateFont.lineHeight - lunarDateFont.lineHeight) / 2.0f;
    
    [date drawInRect:CGRectMake(targetX, targetY + targetGap, kVRGCalendarViewDayWidth, kVRGCalendarViewDayHeight) withFont:dateFont lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentCenter];
    
    /**隐藏农历*/
//    [lunarDate drawInRect:CGRectMake(targetX, targetY + targetGap + dateFont.lineHeight, kVRGCalendarViewDayWidth, kVRGCalendarViewDayHeight) withFont:lunarDateFont lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentCenter];
    
    
    
    //画小图标
//    CGRect alermRect = CGRectMake(targetX + kVRGCalendarViewDayWidth - 2.0f - 15.0f, targetY + 2.0f, 15.0f, 15.0f);
//    CGContextSetFillColorWithColor(context, [UIColor colorWithHexString:@"0xff4500" alpha:1.0f].CGColor);
//    CGContextFillEllipseInRect(context, alermRect);
    
    //画小图标中的字
    CGRect alermTextRect = CGRectMake(targetX + kVRGCalendarViewDayWidth - 2.0f - 15.0f, targetY + 2.0f + (15.0f - lunarDateFont.lineHeight) / 2.0f, 15.0f, 15.0f);
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    [@"3" drawInRect:alermTextRect withFont:lunarDateFont lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentCenter];

}

#pragma mark - Draw image for animation
-(UIImage *)drawCurrentState {
    float targetHeight = kVRGCalendarViewTopBarHeight + [self numRows]*kVRGCalendarViewDayHeight+1;
    
    UIGraphicsBeginImageContext(CGSizeMake(kVRGCalendarViewWidth, targetHeight-kVRGCalendarViewTopBarHeight));
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, -kVRGCalendarViewTopBarHeight);    // <-- shift everything up by 40px when drawing.
    [self.layer renderInContext:c];
    UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

#pragma mark - Init
-(id)init {
    self = [super initWithFrame:CGRectMake(0, 0, kVRGCalendarViewWidth, 0)];
    if (self) {
        self.contentMode = UIViewContentModeTop;
        self.clipsToBounds=YES;
        isAnimating = NO;
        
        // 添加日历标题
        self.labelCurrentMonth = [[UILabel alloc] initWithFrame:CGRectMake(34, 7, kVRGCalendarViewWidth-68, 40)];
        
        self.labelCurrentMonth.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:19];
        self.labelCurrentMonth.textColor = [UIColor colorWithHexString:@"0x323232" alpha:1.0f];
        self.labelCurrentMonth.textAlignment = NSTextAlignmentCenter;
        [self addSubview:self.labelCurrentMonth];
        
        
        // 添加两边按钮
        CGRect todayFrame = CGRectMake(10, 0, 30, 30);
        [self addCalendarBtnWithImage:@"today" SeleImage:nil Frame:todayFrame Target:@selector(todayBtnDidClick:)];
        
        CGRect upBtnFrame = CGRectMake(CGRectGetMaxX(self.labelCurrentMonth.frame) - 75, 0, 40, 40);
        [self addCalendarBtnWithImage:@"down" SeleImage:@"up" Frame:upBtnFrame Target:@selector(upBtnDidclick:)];
        
        [self addCalendarBtnWithImage:@"right" SeleImage:nil Frame:CGRectMake(kVRGCalendarViewWidth - 40, 0, 40, 40) Target:@selector(nextMonthBtnDidClick:)];
        
        [self addCalendarBtnWithImage:@"left" SeleImage:nil Frame:CGRectMake(kVRGCalendarViewWidth - 40 - 20, 0, 40, 40) Target:@selector(preiouMonthBtnDidClick:)];
        
        
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        // 设置背景按钮颜色
        button.backgroundColor = WZRGBColor(243, 243, 243);
        [button addTarget:self action:@selector(qiehuanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [button setTitle:@"切换" forState:UIControlStateNormal];
        // 修改切换按钮
        [button setImage:[UIImage imageNamed:@"button-up"] forState:UIControlStateNormal];
//        [button setTitleColor:BlackColor forState:UIControlStateNormal];
//        button.titleLabel.font = Font14;
        [self addSubview:button];
        self.qiehuanBtn = button;
//        button.frameHeight = Font14.lineHeight;
        
        button.frameHeight = kVRGCalendarViewBottomHeight;
        button.frameWidth = kVRGCalendarViewWidth;
        
//        // add workTask view
//        UITableView *taskView = [[UITableView alloc] init];
//        taskView.frameWidth = kVRGCalendarViewWidth;
//        taskView.frameHeight = [UIScreen mainScreen].bounds.size.height;
//        taskView.frame = CGRectMake(0,300, kVRGCalendarViewWidth, taskView.frameHeight - 300);
//        taskView.backgroundColor = [UIColor redColor];
//        [self addSubview:taskView];
        
        
        [self reset]; //so delegate can be set after init and still get called on init
        //        [self reset];

        UISwipeGestureRecognizer *swipLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipLeft)];
        swipLeft.direction = UISwipeGestureRecognizerDirectionLeft;
        [self addGestureRecognizer:swipLeft];
        
        UISwipeGestureRecognizer *swipRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipRight)];
        swipRight.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:swipRight];
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectedDateWithGesture:)];
        [self addGestureRecognizer:tap];

    }
    return self;
}


// 添加日历按钮
- (void)addCalendarBtnWithImage:(NSString *)norImage SeleImage:(NSString *)seleImage Frame:(CGRect)btnFrame Target:(SEL)target {
    
    UIButton *btn = [[UIButton alloc] initWithFrame:btnFrame];
    [btn setImage:[UIImage imageNamed:norImage] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:seleImage] forState:UIControlStateSelected];
    [btn addTarget:self action:target forControlEvents:UIControlEventTouchUpInside];
    btn.adjustsImageWhenHighlighted = NO;
    btn.centerY = self.labelCurrentMonth.centerY;
    [self addSubview:btn];

}

#pragma mark -- monthSelect
- (void)nextMonthBtnDidClick:(UIButton *)sender {
    
    [self swipLeft];
}

- (void)preiouMonthBtnDidClick:(UIButton *)sender {
    
    [self swipRight];
}

#pragma mark -- 点击按钮收起日历
- (void)upBtnDidclick:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(calendarView:dateOptionBtnDidClick:)]) {
        
        [self.delegate calendarView:self dateOptionBtnDidClick:sender];
    }
}

- (void)todayBtnDidClick:(UIButton *)sender {
    
    if ([self.delegate respondsToSelector:@selector(calendarView:todayBtnDidClick:)]) {
        
        [self.delegate calendarView:self todayBtnDidClick:sender];
    }
}

// TODO: 显示一周
- (void)showNextWeek
{

}
- (void)showPreviousWeek
{

    
}
- (void)swipLeft
{
    if (self.qiehuanBtn.selected) {
        [self showNextWeek];
    } else {
        [self showNextMonth];
    }
}

- (void)swipRight
{
    if (self.qiehuanBtn.selected) {
        [self showPreviousWeek];
    } else {
        [self showPreviousMonth];
    }

}
- (void)qiehuanBtnClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    
    if (btn.selected) {
        
        [btn setImage:[UIImage imageNamed:@"button-down"] forState:UIControlStateSelected];
    } else {
        
        [btn setImage:[UIImage imageNamed:@"button-up"] forState:UIControlStateNormal];
    }
    
    [UIView animateWithDuration:0.35f animations:^{
        if (btn.selected) {
            
            [self updateSizeForWeek];
        } else {
            [self updateSize];
        }
    }];
}

#pragma mark -- update Frame
- (void)updateSizeForWeek
{
    self.frameHeight = kVRGCalendarViewTopBarHeight + kVRGCalendarViewDayHeight + 2.0f + self.qiehuanBtn.frameHeight;
    self.qiehuanBtn.y = self.frameHeight - self.qiehuanBtn.height;
    [self setNeedsDisplay];
    if ([self.delegate respondsToSelector:@selector(calendarView:switchedToMonthWithTargetHeight:animated:)]) {
        [self.delegate calendarView:self switchedToMonthWithTargetHeight:self.frameHeight animated:YES];
    }
    
}


-(void)dealloc {
    
    self.delegate=nil;
    self.currentMonth=nil;
    self.labelCurrentMonth=nil;
    self.markedDates=nil;
    self.markedColors=nil;
    
}
@end
